package com.kang.dao.impl;

import com.kang.dao.AgencyDao;
import com.kang.dao.Rh_regionDao;
import com.kang.entity.ServiceInfo;
import com.kang.util.BaseDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 查询代理信息   默认查所有  并分页
 * 因为使用的是级联  默认省份和市是有值的  所以不用判断
 *
 */
public class AgencyDaoImpl implements AgencyDao
{
    @Override
    public List<ServiceInfo> find(int page, int size)
    {
        List<ServiceInfo> list = new ArrayList<ServiceInfo>();
        Connection conn = null;
        PreparedStatement stat = null;
        ResultSet rs = null;
        String sql = "select * from rh_service WHERE 1 = 1 ";
        sql +=" limit ?,?";

        conn = BaseDao.getConnection();
        try {
            stat = conn.prepareStatement(sql);
            stat.setInt(1, page);
            stat.setInt(2, size);

            rs = stat.executeQuery();
            while (rs.next()){
                ServiceInfo sInfo = new ServiceInfo();
                sInfo.setId(rs.getInt("id"));
                sInfo.setUname(rs.getString("uname"));
                sInfo.setRname(rs.getString("rname"));
                sInfo.setPwd(rs.getString("pwd"));
                sInfo.setPhone(rs.getString("phone"));
                sInfo.setEmail(rs.getString("email"));
                sInfo.setUid(rs.getInt("uid"));
                sInfo.setPro_id(rs.getInt("pro_id"));
                sInfo.setCityid(rs.getInt("cityid"));
                Rh_regionDao dao = new Rh_regionDaoImpl();
                sInfo.setRegion(dao.findByType(sInfo.getPro_id()));
                sInfo.setXid(rs.getInt("xid"));
                sInfo.setAddress(rs.getString("address"));
                list.add(sInfo);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeConnection(conn,stat,rs);
        }

        return list;
    }

    @Override
    public int find()
    {
        int count = 0;
        Connection conn = null;
        PreparedStatement stat = null;
        ResultSet rs = null;
        String sql = "select count(1) from rh_service where 1 = 1 ";

        try {
            conn = BaseDao.getConnection();
            stat = conn.prepareStatement(sql);
            rs = stat.executeQuery();
            if (rs.next()) {
                count = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public int delAgency(int id)
    {
        String sql = "delete from rh_service where id = ?";
        Object[] object = {
                id
        };
        return BaseDao.executeUpdate(sql,object);
    }
}
